package com.bdsy.system.web.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.bdsy.common.annotation.Json;
import com.bdsy.common.controller.AbstractController;
import com.bdsy.common.utils.Result;
import com.bdsy.common.utils.StringUtil;
import com.bdsy.common.utils.UUIDUtil;
import com.bdsy.common.utils.UserUtils;
import com.bdsy.common.utils.ValidateUtils;
import com.bdsy.system.annotation.SysLog;
import com.bdsy.system.model.Role;
import com.bdsy.system.model.User;
import com.bdsy.system.model.UserRole;
import com.bdsy.system.service.RoleService;
import com.bdsy.system.service.UserOperationLogService;
import com.bdsy.system.service.UserRoleService;
import com.bdsy.system.service.UserService;
import com.bdsy.system.shiro.Encrypt;
import com.bdsy.system.shiro.ShiroUtils;

/**
 * ClassName:UserController
 * Description: TODO 添加描述.
 * @author   Administrator
 * @version  
 * @since    JDK 1.8
 */
@Controller
@RequestMapping(value = "${web.adminPath}")
public class UserController extends AbstractController{
	
	private static final Logger log = Logger.getLogger(UserController.class);
	@Autowired
	UserOperationLogService logService;
	
	@Autowired
	UserService userService;
    
	@Autowired
	RoleService roleService;
	
	@Autowired
	UserRoleService userRoleService;
	@RequestMapping(value="sysuser")
	public String sysuser(HttpServletRequest request, HttpServletResponse response, Model model) {
		List<Role> list = roleService.getRole();
		model.addAttribute("list", list);
		return "admin/system/sysuser";
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Json
	@RequestMapping(value="userlist")
	public Object userlist(HttpServletRequest request, HttpServletResponse response, Model model) throws ParseException {
	   
		List<Map> list = userService.getUserList();
		for(Map m : list){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(m.get("last_access_time") != null && !"".equals(m.get("last_access_time"))){
				m.put("last_access_time", sdf.format(m.get("last_access_time")));
			}
			if(m.get("create_date") != null && !"".equals(m.get("create_date"))){
				m.put("create_date", sdf.format(m.get("create_date")));
			}
		}
		return list;
	}
	
	@Json
	@SysLog("新增用户")
	@RequiresPermissions("sys:user:save")
	@RequestMapping(value="addUser")
	public Object addUser(HttpServletRequest request, User user,UserRole userRole,String roleId) {
		if(!ValidateUtils.isNotEmpty(user.getUserName())){
			return Result.error("用户名为空!");
		}
		if(!ValidateUtils.isNotEmpty(user.getLoginName())){
			return Result.error("登录用户名为空!");
		}
		if(!ValidateUtils.isNotEmpty(user.getLoginPassword())){
			return Result.error("登录密码为空!");
		}
		//判断用户名是否唯一
		User u = userService.getUsername(user.getLoginName().trim());
	
		String userId;
		if(u == null){
			user.setUserStatus(1);
			boolean flag = true;
			do {
				userId = UUIDUtil.randomUUID();
				User dbUser = userService.getUserById(userId);
				//如果用户id唯一，则直接赋值，不唯一要重新生成用户id
				if(dbUser == null){
					flag = false;
					user.setUserId(userId);
				}
			} while (flag);
			user.setCreateDate(new Date());
			//去掉输入框的错误输入的空格
			user.setUserName(StringUtil.replaceBlank(user.getUserName()));
			user.setLoginName(StringUtil.replaceBlank(user.getLoginName()));
			user.setLoginPassword(user.getLoginPassword().trim());
			String pwd = Encrypt.md5(user.getLoginPassword(), user.getLoginName());
			user.setLoginPassword(pwd);
			boolean result = userService.addUser(user);
			if (result) {
				userRole.setUserRoleId(UUIDUtil.randomUUID());
				userRole.setUserId(userId);
				userRole.setRoleId(roleId);
				userRoleService.addUserRole(userRole);
				return Result.ok("添加成功");
			}else{
				return Result.error("添加失败");
			}
		}else{
			return Result.error("用户名已存在!");
		}
	}
	
	@Json
	@RequestMapping(value="checkLoginNameUrl")
	public boolean checkLoginName(HttpServletRequest request,String loginName){
		//判断用户名是否唯一
		User u = userService.getUsername(StringUtil.replaceBlank(loginName));
		if(u == null){
			return true;
		}
		return false;
	}
	
	@Json
	@SysLog("修改用户")
	@RequiresPermissions("sys:user:update")
	@RequestMapping(value="updateUser")
	public Result updateUser(HttpServletRequest request, User user,UserRole userRole,String userId,String roleId) {
		String loginPassword = userService.getLoginPasswordById(user.getUserId());
		User userById = userService.getUserByUid(user.getUserId());
		if(loginPassword !=null && loginPassword.trim().length()>0){
			if(!loginPassword.equals(user.getLoginPassword())){
			String encryptLoginPassword=Encrypt.md5(user.getLoginPassword(), userById.getLoginName());
			user.setLoginPassword(encryptLoginPassword);
			}
		}
		userById.setUserStatus(user.getUserStatus());
		userById.setLoginName(user.getLoginName());
		userById.setUserName(user.getUserName());
		userById.setLoginPassword(user.getLoginPassword());
		boolean result = userService.updateUser(userById);
		if (result) {
			userRole.setRoleId(roleId);
			userRole.setUserId(userId);
			userRoleService.updateUserRoleByUserId(userRole);
    		return Result.ok("修改成功");
		}else{
			return Result.error("修改失败");
		}
	}
	
	@Json
	@SysLog("删除用户")
	@RequiresPermissions("sys:user:delete")
	@RequestMapping(value="deleteUserById")
	public Object deleteUserById(String pIds) {
		List<String> list = JSON.parseArray(pIds, String.class);
		userRoleService.deleteUserRoleByUserId(list);
		boolean result = userService.deleteUserById(list);
		if (result) {
    		return Result.ok("删除成功");
		}else{
			return Result.error("删除失败");
		}
	}
	
	@Json
	@RequestMapping(value="getUserRole")
	public Object getUserRoleByUserId(HttpServletRequest request,String userId){
		List<Role> list = roleService.getRoleById(userId);
		if(list !=null && list.size()>0){
			Role role = list.get(0);
			return role;
		}
		return null;
	}
	
	@Json
	@RequestMapping(value="userInfo")
	public Result info(){
		return Result.ok().put("user", getUser());
	}
	
	@SysLog("修改密码")
	@Json
	@RequestMapping(value="/editLogPassword")
	public Result editLogPassword(HttpServletResponse response,User user,String newPassword){
		
		Subject subject = ShiroUtils.getSubject();
		User loginUser = (User) subject.getPrincipal();
		boolean result=false;
		String loginPassword = userService.getLoginPasswordById(user.getUserId());
		String oldPassword = Encrypt.md5(user.getLoginPassword(), user.getLoginName());
		//对比旧密码输入是否正确
		if(!oldPassword.equals(loginPassword)){
			return Result.error("原密码错误!");
		}else{
			if(loginPassword !=null && newPassword.trim().length()>0){
				String encryptLoginPassword=Encrypt.md5(newPassword, loginUser.getLoginName());
				if(!encryptLoginPassword.equals(user.getLoginPassword())){
				loginUser.setLoginPassword(encryptLoginPassword);
				result = userService.updateUser(loginUser);
				}
			}
		}
		if (result) {
    		return Result.ok("密码修改成功,请重新登录!");
		}else{
			return Result.error("密码修改失败!");
		}
	}
}

